package oxing.core;

import java.util.concurrent.atomic.AtomicReference;

public class Message implements Runnable {
	private final AtomicReference<Message> pool;
	Message next;
	public int what;
	public int arg1;
	public int arg2;
	public Object obj;

	protected Message() {
		pool = null;
	}

	protected Message(AtomicReference<Message> pool) {
		this.pool = pool;
	}

	private final static AtomicReference<Message> sPool = new AtomicReference<Message>(null);

	public static Message obtain(int what) {
		Message m;
		if (what < 0)
			throw new IllegalArgumentException("[Message]:" + what);
		while ((m = sPool.get()) != null && !sPool.compareAndSet(m, m.next))
			;
		if (m != null)
			m.next = null;
		else
			m = new Message(sPool);
		m.what = what;
		return m;
	}

	public final void sendTo(MessagePool handler) {
		if (handler == null || what < 0) {
			recycle();
			return;
		}
		handler.addMessage(this);
	}

	protected void recycle() {
		if (pool == null)
			return;
		what = -1;
		arg1 = arg2 = 0;
		obj = null;
		next = pool.getAndSet(this);
	}

	public void run() {

	}
}